

//
//  DHSetandHelpViewController.m
//  DHKuaiYi
//
//  Created by 韩旭 on 16/11/15.
//  Copyright © 2016年 30-陈辉华. All rights reserved.
//

#import "DHSetandHelpViewController.h"
#import <Masonry.h>
#import "DHSetandHelpTableViewCell.h"
#import "DHAdvicesViewController.h"
#import <SVProgressHUD.h>

@interface DHSetandHelpViewController ()<UITableViewDataSource,UITableViewDelegate>

/* 图片数组 */
@property (strong, nonatomic) NSArray *imgArray;
/* 标题数组 */
@property (strong, nonatomic) NSArray *labelArray;
/* 背景图片 */
@property (strong, nonatomic) UIImageView *backgroundImg;
/* tableView */
@property (nonatomic, weak) UITableView *tableView;

@end

@implementation DHSetandHelpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /*----监听登陆状态----*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveLoginStatusChanged) name:LOGIN_STATUS_CHANGED object:nil];
    
    /*----设置SVP样式----*/
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
}

- (void)xhhSetupSubviews {
    
    UIImageView *backgroundImg = [[UIImageView alloc]init];
    self.backgroundImg=backgroundImg;
    backgroundImg.image = [UIImage imageNamed:@"pic_hd_1.png"];
    [self.view addSubview:backgroundImg];
    
    //自动布局
    [backgroundImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    UITableView *setandHelpTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    setandHelpTableView.backgroundColor= [UIColor clearColor];
    
    //记录属性
    self.tableView = setandHelpTableView;
    
    //设置数据源对象
    setandHelpTableView.dataSource = self;
    setandHelpTableView.delegate = self;
    [self.view addSubview:setandHelpTableView];
    
    //注册cell
    [setandHelpTableView registerClass:[DHSetandHelpTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    //自动布局
    [setandHelpTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    self.labelArray = [NSArray arrayWithObjects:@"意见反馈",@"加符号说明",@"修改密码", @"清理缓存", @"注销", nil];
    self.imgArray = [NSArray arrayWithObjects:
                     @"medtronic_phone.jpg",
                     @"medtronic_service.jpg",
                     @"medtronic_story.jpg",
                     @"medtronic_vip_zone.jpg",
                     @"service_private_manager_s.jpg",
                     nil];
}

#pragma mark -UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DHSetandHelpTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.label.text = self.labelArray[indexPath.item];
    cell.icon.image = [UIImage imageNamed:self.imgArray[indexPath.item]];
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSUInteger row = indexPath.row;
    
    switch (row) {
        case 0:
        {
            DHAdvicesViewController *advicesViewController=[[DHAdvicesViewController alloc]init];
            [self.navigationController pushViewController:advicesViewController animated:YES];
        }
            break;
        case 1:
            [self.navigationController pushViewController:[self getControllerWithClassName:@"DHBaseViewController"] animated:YES];
            break;
        case 2:
            [self.navigationController pushViewController:[self getControllerWithClassName:@"DHBaseViewController"] animated:YES];
            break;
        case 3:
            [self ClearMemoryPop];
            break;
        case 4:
            [self logoutCurrentAccount];
            break;
            
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return [[UIApplication sharedApplication]statusBarFrame].size.height + self.navigationController.navigationBar.bounds.size.height;
}

- (void)xhhSetupNavigationItems {
    self.title= @"设置与帮助";
}

#pragma mark -清理缓存
- (void)myClearCacheAction {
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                   , ^{
                       NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                       
                       NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                       //文件个数
                       NSLog(@"files :%lu",(unsigned long)[files count]);
                       for (NSString *p in files) {
                           NSError *error;
                           NSString *path = [cachPath stringByAppendingPathComponent:p];
                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                           }
                       }
                       [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
}

- (void)clearCacheSuccess {
    
    NSLog(@"清理成功");
    
}

- (void)ClearMemoryPop {
    
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    CGFloat fileSize = [self folderSizeAtPath:cachPath];
    
    NSString *Memory = [NSString stringWithFormat:@"缓存大小：%.2lfMB",fileSize];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"你确定要清理缓存？" message:Memory preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"清除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [SVProgressHUD show];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD showSuccessWithStatus:@"清理成功"];
            delay(1.2);
            
            //调用清理缓存
            [self myClearCacheAction];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                
            });
        });
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (CGFloat)folderSizeAtPath:(NSString *)folderPath {
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) {
        return 0;
    }
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString *fileName = nil;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    
    return folderSize/(1024.0*1024.0);
}

- (long long)fileSizeAtPath:(NSString *)filePath {
    
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

#pragma 注销登陆
- (void)logoutCurrentAccount {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"你确定要登出？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"登出" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        if ([XHHUserDefaultsTool objetForKey:CURRENT_LOGIN_ACCOUNT_KEY]) {
            [XHHUserDefaultsTool saveObject:nil forKey:CURRENT_LOGIN_ACCOUNT_KEY];
            [SVProgressHUD showSuccessWithStatus:@"登出成功！"];
            delay(1.5);
            
            [[NSNotificationCenter defaultCenter] postNotificationName:LOGIN_STATUS_CHANGED object:nil];
        } else {
            [SVProgressHUD showErrorWithStatus:@"你还没登陆哦"];
            delay(1.5);
        }
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)didReceiveLoginStatusChanged {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
